import { defineStore } from 'pinia';

export const useDownloadStore = defineStore('download', {
  state: () => ({
    downloads: [],
    nextId: 1,
    settings: {
      defaultPath: ''
    }
  }),

  getters: {
    activeDownloads: (state) => {
      return state.downloads.filter(d => 
        d.status === 'downloading' || d.status === 'pending'
      );
    },
    
    completedDownloads: (state) => {
      return state.downloads.filter(d => d.status === 'completed');
    },
    
    totalProgress: (state) => {
      const active = state.downloads.filter(d => d.status === 'downloading');
      if (active.length === 0) return 0;
      
      const totalPercentage = active.reduce((sum, d) => sum + (d.progress?.percentage || 0), 0);
      return totalPercentage / active.length;
    }
  },

  actions: {
    addDownload(config) {
      const download = {
        id: this.nextId++,
        filename: config.filename,
        url: config.url || '',
        savePath: config.savePath,
        peers: config.peers,
        shardCount: config.shardCount,
        rsConfig: config.rsConfig,
        status: 'pending',
        progress: {
          total: 0,
          downloaded: 0,
          percentage: 0,
          shards: { total: 0, downloaded: 0, required: 0 },
          speed: 0,
          eta: -1
        },
        createdAt: new Date(),
        error: null
      };
      
      this.downloads.push(download);
      return download.id;
    },

    updateProgress(id, progress) {
      const download = this.downloads.find(d => d.id === id);
      if (download) {
        download.progress = progress;
        download.status = 'downloading';
      }
    },

    setComplete(id, result) {
      const download = this.downloads.find(d => d.id === id);
      if (download) {
        download.status = 'completed';
        download.completedAt = new Date();
        download.finalPath = result.path;
      }
    },

    setError(id, error) {
      const download = this.downloads.find(d => d.id === id);
      if (download) {
        download.status = 'error';
        download.error = error;
      }
    },

    setPaused(id) {
      const download = this.downloads.find(d => d.id === id);
      if (download) {
        download.status = 'paused';
      }
    },

    removeDownload(id) {
      const index = this.downloads.findIndex(d => d.id === id);
      if (index !== -1) {
        this.downloads.splice(index, 1);
      }
    },

    updateSettings(newSettings) {
      this.settings = { ...this.settings, ...newSettings };
      // 保存到localStorage
      if (typeof localStorage !== 'undefined') {
        localStorage.setItem('downloadSettings', JSON.stringify(this.settings));
      }
    },

    loadSettings() {
      if (typeof localStorage !== 'undefined') {
        const saved = localStorage.getItem('downloadSettings');
        if (saved) {
          try {
            this.settings = { ...this.settings, ...JSON.parse(saved) };
          } catch (e) {
            console.error('Failed to load settings:', e);
          }
        }
      }
    }
  }
});


